import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
import {
  apiLogin,
  apiRegister
} from "../../service/api/user";

Page({

  data: {
    username: '',
    password: '',
  },

  //输入用户名
  inputName: function (e) {
    this.setData({
      username: e.detail
    })
  },

  //输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail
    })
  },

  // 跳转到首页
  toHome() {
    wx.switchTab({
      url: '../index/index',
    })
  },

  //登陆
  login() {
    const { password, username } = this.data;
    if (!password || !username) {
      Toast("请输入完整")
      return;
    }
    apiLogin({
      password,
      username,
    }).then(res => {
      if (res?.data?.id) {
        wx.setStorageSync('userinfo', username)
        Toast.success("登录成功")
        setTimeout(() => {
          this.toHome()
        }, 1000)
      } else {
        Toast.fail("登录失败")
      }
    })
  },

  //注册
  register() {
    const { password, username } = this.data;
    if (!password || !username) {
      Toast("请输入完整")
      return;
    }
    apiRegister({
      password,
      username,
    }).then(res => {
      if (res?.data?.id) {
        wx.setStorageSync('userinfo', username)
        Toast.success("注册成功")
        setTimeout(() => {
          this.toHome()
        }, 1000)
      } else {
        Toast.fail("注册失败")
      }
    })
  },
})